<?php
namespace Hive;
/**
 * Company Object. 
 * 
 * It represant a Company.
 *
 * @author Xavier VILAIN
 * @package hr
 * @property int 	$compid				Company Id
 * @property string $company_keyname	Cleanup Name of the company
 * @property string $company_name		Real Unicode Name
 * @property string $parentid			Id Company Parent 
 * @property string $website			Company Website
 * @property date 	$description 		Description
 * @property string $size				Size
 * @property int 	$adrid				Address Id (can be null)
 * @property string $logo				Logo Filename 
 * @property bool 	$loekz 				Deletion Flag if true is an been deleted
 */
use Fox\Dao\SqlFragment;

class Company extends \Fox\Object\Versioned {
	
	/**
	 * Bundle Directory
	 * @var string
	 */
	const BUNDLE = 'company';
	
	/**
	 * Task Reference id
	 * @var int
	 */
	const TASK_REFERENCE = 3;
	
	/**
	 * Default Address
	 * @var int
	 */
	const ADDRESS_TYPE_DEFAULT = 1;
	
	/**
	 * Link to the documents
	 * @var string
	 */
	const LINK_DOCUMENTS = 'documents';

	/**
	 * Link to default address
	 * @var Fox\Common\Address
	 */
	const LINK_DEFAULT_ADDRESS = 'defaultAddress';

	/**
	 * Link to default address
	 * @var Fox\Common\Address
	 */
	const LINK_ADDRESSES = 'addresses';
	
	/**
	 * 
	 * Reverse link to the parent company
	 * @var string
	 */
	const LINK_PARENT_COMPANY = 'parentCompany';
	
	/**
	 * 
	 * Link to sub companies
	 * @var string
	 */
	const LINK_SUB_COMPANIES = 'subCompanies';
	
	/** 
	 * @param array $fields
	 */
	protected function afterSetFields(array $fields) {
		$this->company_keyname = self::cleanup($fields['company_name']);
	}
	
	/**
	 * Cleanup Company Name (remove accent, convert to lower case...)
	 */
	static function cleanup($companyName)
	{
		$keyname = null;
		$companyName = \Fox\Utilities\Text::removeAccents(trim($companyName));
		// remove non caracters
		$companyName = strtolower(preg_replace('/[^0-9a-zA-Z\s]/','',$companyName));
		// replace space by -
		foreach(explode(' ',$companyName) as $part) {
			if(!empty($part)) {
				$keyname .= empty($keyname) ? $part : '-'.$part;
			}
		}
		return $keyname;
	}
	
	/**
	 * Check if a company Exist
	 */
	static function lookup($companyName)
	{
		$cleanName = self::cleanup($companyName);
		$finder = new Company();
		$result = $finder->find(new \Fox\Dao\SqlFragment('company_keyname = ?', array($cleanName)));
		if(count($result) > 0)
		{
			return $result[0];
		}
		return false;
	}
	
	/**
	 * Name of the company
	 * @return string
	 */
	public function name() {
		return $this->company_name;
	}
	
	/**
	 * Return logo source
	 * @TODO build the logo import part
	 */
	public function logo() {
		$logo = $this->logo;
		if(!empty($logo)) {
			return _APPLICATION_IMAGES_COMPANIES_URL_.'thumb_'.$logo;
		}
		return _APPLICATION_DEFAULT_COMPANIES_PICTURE_;
	}
	
	/**
	 * Return company category
	 * @TODO build the logo import part
	 */
	public function category()
	{
		return null;
	}

	/**
	 * Find all associated tasks
	 * @return array
	 */
	public function tasks($displayDelete = false)
	{
		if(empty($this->tasks)) {
			$finder = \Fox\Dao::finder(\Shama\Task::className())
							->orderBy('duedate','DESC');
			if(!$displayDelete)	{
				$finder->where('status != ?',array(\Shama\Task::STATUS_CLOSED));
			}			
							
			$finder->follow(\Shama\Task::LINK_REFERENCES)
								->where('reference = ? AND reference_id= ?',
									array(self::TASK_REFERENCE,$this->getId()));					
			$this->tasks = $finder->find();
		}
		return $this->tasks;
	}
	
	/**
	 * Count contacts per type
	 * @return array
	 */
	public function countContacts() {
		$infos = \Fox\Dao::infos(\Hive\Ressource\Experience::className());
		$query = $infos->handle()->createQueryBuilder();
		$query->select('current,importance,COUNT(*) as nb')
			->from($infos->tableName(),'exp')
			->groupBy('current','importance');
		$fragment = new SqlFragment('compid = ?',array($this->compid));
		$result = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
		$final['old'] = $final['vip'] = $final['all'] = 0;
		foreach($result as $data) {
			if($data['importance'] > 0) {
				$final['vip'] = $data['nb'];
			} elseif($data['current']) {
				$final['all'] = $data['nb'];
			} else {
				$final['old'] = $data['nb'];
			}
		}
		$final['all'] += $final['vip'];
		return $final;
	}
	
	/**
	 * Find Company Parent Name
	 * @return string
	 */
	public function parentName() {
		try {
			$parent = \Fox\Dao::load(self::className(),$this->parentid);
			return $parent->name();
		} catch(Fox\Object\Exception\NotExist $e) {
			return null;
		}
	} 
}
\Fox\Dao::infos(Company::className(),new \Fox\Object\Info('companies', \Fox\Databases::DB_APP));

// Link To Documents (Order, Contract...)
\Fox\Object\Links::add(\Fox\Dao::link(Company\Document::className(),Company\Document::LINK_COMPANY)
	->to(Company::className(), Company::LINK_DOCUMENTS)
	->on('compid')
	->versionFrom()
);

// Link To Default Address
\Fox\Object\Links::add(\Fox\Dao::link(Company\Address\Link::className(),Company\Address\Link::LINK_COMPANY)
	->to(Company::className(), Company::LINK_DEFAULT_ADDRESS)
	->on('compid')
	->where('type = ?',array(1))
	->oneToOne()
);

// Link To All Address
\Fox\Object\Links::add(\Fox\Dao::link(Company\Address\Link::className(),Company\Address\Link::LINK_COMPANY_REVERSE)
	->to(Company::className(), Company::LINK_ADDRESSES)
	->on('compid')
	->versionFrom()
);
// Link To Sub Companies
\Fox\Object\Links::add(\Fox\Dao::link(Company::className(),Company::LINK_PARENT_COMPANY)
	->to(Company::className(), Company::LINK_SUB_COMPANIES)
	->on('parentid')
);